# -*- coding: utf-8 -*-
"""
    xfree.cli.users
    ~~~~~~~~~~~~~~~~~~~
    文件描述：这个模块包含所有用户相关的命令。
    作者：xfree
    邮箱：cy_83k@qq.com
"""

import os
import sys

import click
from sqlalchemy.exc import IntegrityError

from xfree.cli.main import xfree
from xfree.cli.utils import EmailType, XFreeCLIError, prompt_save_user
from xfree.user.models import User


@xfree.group()
def users():
    """用于创建、更新或删除用户。"""
    pass


@users.command("new")
@click.option("--username", "-u", help="用户的用户名。")
@click.option("--email", "-e", type=EmailType(), help="用户的电子邮件地址。")
@click.option("--password", "-p", help="用户的密码。")
@click.option(
    "--group",
    "-g",
    help="用户的用户组。",
    type=click.Choice(["admin", "super_mod", "mod", "member"]),
)
def new_user(username, email, password, group):
    """创建一个新用户。省略任何选项以使用交互模式。"""
    try:
        user = prompt_save_user(username, email, password, group)

        click.secho(
            "[+] 创建了用户 {}，其电子邮件地址为 {}，在 {} 用户组中。".format(
                user.username, user.email, user.primary_group.name
            ),
            fg="cyan",
        )
    except IntegrityError:
        raise XFreeCLIError(
            "无法创建用户，因为用户名或电子邮件地址已被占用。",
            fg="red",
        )


@users.command("update")
@click.option("--username", "-u", help="用户的用户名。")
@click.option("--email", "-e", type=EmailType(), help="用户的电子邮件地址。")
@click.option("--password", "-p", help="用户的密码。")
@click.option(
    "--group",
    "-g",
    help="用户的用户组。",
    type=click.Choice(["admin", "super_mod", "mod", "member"]),
)
def change_user(username, email, password, group):
    """更新用户。省略任何选项以使用交互模式。"""

    user = prompt_save_user(username, email, password, group, only_update=True)
    if user is None:
        raise XFreeCLIError(
            "用户名 {} 的用户不存在。".format(username), fg="red"
        )

    click.secho("[+] 用户 {} 已更新。".format(user.username), fg="cyan")


@users.command("delete")
@click.option("--username", "-u", help="用户的用户名。")
@click.option(
    "--force",
    "-f",
    default=False,
    is_flag=True,
    help="无需确认即删除用户。",
)
def delete_user(username, force):
    """删除用户。"""
    if not username:
        username = click.prompt(
            click.style("用户名", fg="magenta"),
            type=str,
            default=os.environ.get("USER", ""),
        )

    user = User.query.filter_by(username=username).first()
    if user is None:
        raise XFreeCLIError(
            "用户名 {} 的用户不存在。".format(username), fg="red"
        )

    if not force and not click.confirm(click.style("你确定吗？", fg="magenta")):
        sys.exit(0)

    user.delete()
    click.secho("[+] 用户 {} 已删除。".format(user.username), fg="cyan")